import { reactControl, ReactViewState, ReactView, ReactViewControl } from "pao-aop-client";

import React from "react";

import { addon, Ref, getObject, log } from "pao-aop";
import { ISingleProductSignService, ProductSignCondition, SingleProductSign } from "src/models/singleProductSign";
// import { SignFrameLayout } from "src/projects/industryInternetSign/layout/sign-manage-layout";
import { NTOperationTable } from "src/business/components/operation-table";
import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { IProductTypeService } from "src/models/productType";
import { onRowSkipClick, change_structure, ROUTE_PATH, isPermission } from "../../app/util-tool";
import Menu, { ClickParam } from "antd/lib/menu";
import { message } from "antd";
import { PermissionList } from "../../app/permission";
/**
 * 组件：单品标识列表页面状态
 */
export interface SingleProductViewState extends ReactViewState {
    /** 单品标识列表数据源 */
    data_source?: SingleProductSign[];
    /** 当前第几页 */
    page?: number;
    /** 当前每页数 */
    pageSize?: number;
    /** 数据总条数 */
    total_data?: number;
    /** 查询条件对象 */
    condition?: ProductSignCondition;
    /** 产品类型列表 */
    product_data?: any;
    /** 行选中对象 */
    row_select_data?: any;
    /** 行操作使能 */
    row_operation_enable?: boolean;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：单品标识列表页面
 * 描述
 */
export class SingleProductView extends ReactView<SingleProductViewControl, SingleProductViewState> {
    private columns_data_source = [{
        title: '单品名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500
    }, {
        title: '产品类型',
        dataIndex: 'product_type',
        key: 'product_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let product = this.state.product_data;
            if (text && product) {
                return product.get(text) ? product.get(text) : text;
            }
        }
    }, {
        title: '单品标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
        render: (text: string, record: any, index: any) => {
            return <a onClick={() => onRowSkipClick(this.props, record, index, ROUTE_PATH.singleProductDetailView)}>{text}</a>;
        }
    }, {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    constructor(props: SingleProductViewControl) {
        super(props);
        this.state = {
            page: 1,
            pageSize: 10,
            row_operation_enable: true,
            row_select_data: [],
            loading: false
        };
    }
    /** 分页回调事件 */
    pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            page: contents,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, contents, this.state.pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            pageSize: pageSize,
            loading: true
        });
        this.queryList(this.state.condition ? this.state.condition! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 删除按钮回调事件 */
    onClickDel = (contents: any) => {
        console.log("删除按钮返回值", contents);
        this.setState({
            loading: true
        });
        this.deleteDeatail([contents.id])
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("SingleProductDetailViewControl-delete", error.message);
            });
    }
    /** 自定义图标按钮回调事件 */
    onIconClick = (type: string, contents: any) => {
        if ('icon_edit' === type) {
            this.props.history!.push(ROUTE_PATH.changeSingleProductView + `/${contents.id}`);
        }
    }
    // 初始化服务
    singleProductSignService?() {
        return getObject(this.props.singleProductSignService_Fac!);
    }
    // 初始化产品类型服务
    productTypeService?() {
        return getObject(this.props.productTypeService_Fac!);
    }
    componentDidMount() {
        let condition: ProductSignCondition = {};
        this.setState({
            loading: true
        });
        this.queryList(condition, 1, 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    // 删除单品详情信息
    async deleteDeatail(id: string[]) {
        const result = await this.singleProductSignService!()!.delete_single!(id)!;
        message.info("删除" + (result ? '成功' : '失败'));
        this.queryList({}, 1, 10)
            .then(() => { })
            .catch(error => {
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    // 查询列表信息
    async queryList(condition: ProductSignCondition, page: number, count: number) {
        const data = await this.singleProductSignService!()!.get_single_list!(condition, page, count)!;
        const product_data = await this.productTypeService!()!.get_product_type_list!()!;
        let product_map = change_structure('product_type_name', product_data!.result);
        this.setState({
            total_data: data ? data!.total : 0, // 应当取接口返回的总数
            data_source: data ? data!.result : [],
            product_data: product_map,
            row_operation_enable: this.state.row_operation_enable ? true : (data!.total === 0 ? true : false)
        });
    }

    // 查询回调
    private searchCategory = (e: any, val: any) => {
        this.setState({
            condition: val,
            page: 1,
            loading: true
        });
        this.queryList(val, 1, this.state.pageSize ? this.state.pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    // 重置回调
    private reset = () => {
        console.log("重置回调");
        this.setState({
            condition: {}
        });
    }
    // 新增单品标识按钮方法
    private addSingleProduct = () => {
        this.props.history!.push(ROUTE_PATH.changeSingleProductView);
    }
    /** 批量操作 */
    private handleMenuClick = (e: ClickParam) => {
        console.log('click', e);
        if (e.key === "delete") {
            let ids: string[] = this.state.row_select_data.map((e: SingleProductSign, i: any) => e.id);
            this.setState({ row_operation_enable: false, loading: true });
            this.deleteDeatail(ids)
                .then(() => {
                    this.setState({
                        loading: false
                    });
                })
                .catch(error => {
                    this.setState({
                        loading: false
                    });
                    log("SingleProductDetailViewControl-delete", error.message);
                });
        }
    }

    /** 行选中回调 */
    private handleRowSelect = (e: any) => {
        console.log(e);

        if (e.length === 0) {
            this.setState({
                row_operation_enable: true
            });
        } else {
            this.setState({
                row_select_data: e,
                row_operation_enable: false
            });
        }
    }
    render() {
        const redeirect = isPermission ? isPermission!(PermissionList.SingleProduct_Select) : undefined;
        if (redeirect) {
            return redeirect;
        }
        const menu = (
            <Menu onClick={this.handleMenuClick}>
                <Menu.Item key="delete">删除</Menu.Item>
            </Menu>
        );

        let sign_frame_props = {
            loading: this.state.loading,
            edit_form_items_props: [{
                type: InputType.input,
                label: "单品名称",
                decorator_id: "handle_name",
                default_value: "",
                option: {
                    placeholder: "请输入单品名称"
                }
            },
            {
                type: InputType.input,
                label: "单品标识",
                decorator_id: "handle_code",
                default_value: "",
                option: {
                    placeholder: "请输入单品标识"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date",
            }],
            btn_props: [{
                label: '新建单品标识',
                btn_method: this.addSingleProduct,
                icon: 'plus'
            }],
            draw_down_btn: {
                menu: menu,
                label: "批量操作",
                enable: this.state.row_operation_enable
            },
            showTable: (
                <NTOperationTable
                    data_source={this.state.data_source}
                    on_row_selection={this.handleRowSelect}
                    columns_data_source={this.columns_data_source}
                    on_click_del={this.onClickDel}
                    // onClick={this.onRowClick}
                    on_icon_click={this.onIconClick}
                    other_label_type={[{ type: 'icon', label_key: 'icon_edit', label_parameter: { icon: 'antd@edit' } }]}
                    table_size='middle'
                    showHeader={true}
                    bordered={false}
                    total={this.state.total_data}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.total_data ? this.state.total_data : 0) / 10)}
                    show_footer={true}
                    page_on_click={this.pageOnCick}
                    show_size_change={this.showSizeChange}
                />),
            search_cb: this.searchCategory,
            reset_cb: this.reset
        };

        return (
            <SignFrameLayout {...sign_frame_props} />
        );
    }
}

/**
 * 控件：单品标识列表页面
 * 控制单品标识列表页面
 */
@addon('SingleProductView', '单品标识列表页面', '控制单品标识列表页面')
@reactControl(SingleProductView, true)
export class SingleProductViewControl extends ReactViewControl {
    /**
     * 单品标识服务
     */
    public singleProductSignService_Fac?: Ref<ISingleProductSignService>;
    /** 
     * 产品类型服务
     */
    public productTypeService_Fac?: Ref<IProductTypeService>;
}